<template>
  <div class="margin-top">
    <el-card class="margin-bottom">
      <div slot="header" class="clearfix relative">
        <span class="title-icon">总计</span>
      </div>
      <el-row :gutter="30" type="flex">
        <el-col :span="4">
          <el-row class="row-item">
            <el-col :span="12">
              应收：
            </el-col>
            <el-col :span="12">
              {{ receiveTotalCost }} {{ standardCurrency }}
            </el-col>
          </el-row>
          <el-row class="row-item">
            <el-col :span="12">
              应付：
            </el-col>
            <el-col :span="12">
              {{ payTotalCost }} {{ standardCurrency }}
            </el-col>
          </el-row>
          <el-row class="row-item">
            <el-col :span="12">
              利润：
            </el-col>
            <el-col :span="12">
              {{
                (Number(receiveTotalCost) * 1000 -
                  Number(payTotalCost) * 1000) /
                  1000
              }}
              {{ standardCurrency }}
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="10" class="border-lr">
          <el-row class="row-item">
            <el-col :span="24">
              应收公司合计：
            </el-col>
          </el-row>
          <el-row class="row-item" v-for="(item, k) in receiveMap" :key="k">
            <el-col :span="24">
              {{ k }}：
              <span v-for="(m, n) in item" :key="m" :value="n">
                {{ m }} {{ n }}
              </span>
            </el-col>
          </el-row>
        </el-col>
        <el-col
          :span="10"
          v-if="!verifyShow.isSaler && !verifyShow.saleAssistant"
        >
          <el-row class="row-item">
            <el-col :span="24">
              应付公司合计：
            </el-col>
          </el-row>
          <el-row class="row-item" v-for="(item, k) in payMap" :key="k">
            <el-col :span="24">
              {{ k }}：
              <span v-for="(m, n) in item" :key="m" :value="n">
                {{ m }} {{ n }}
              </span>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-card>
    <el-card class="margin-bottom btn-header" v-if="verifyShow.receView">
      <div slot="header" class="clearfix relative">
        <span class="title-icon">应收</span>
        <div v-if="isEdit" class="header-save-btn">
          <el-button
            size="mini"
            type="text"
            style="margin-right: 30px;"
            @click="repairAllReceiveSynToAmoeba"
          >
            <el-tooltip
              effect="light"
              placement="bottom"
              content="应收(未结转)重新同步到阿米巴"
            >
              <i class="el-icon-refresh" style="font-size:20px"></i>
            </el-tooltip>
          </el-button>
          <el-tooltip
            v-if="verifyShow.editRece"
            effect="light"
            placement="bottom"
            content="复制应收"
          >
            <i
              class="el-icon-document-copy text-blue text-xl margin-right"
              @click="copyReceivableinfo"
            ></i>
          </el-tooltip>

          <el-button
            v-if="verifyShow.createRece"
            type="text"
            size="mini"
            @click="addReceivable"
          >
            新增
          </el-button>

          <!-- <el-button type="text" size="mini" @click="saveReceivable">
            保存
          </el-button> -->
        </div>
      </div>

      <HotTable
        ref="receivableHotTable"
        :isEdit="isEdit"
        :templateName="`Receivable`"
        :templateData.sync="receivableData"
        :templateOptUser="optUser"
        :receveToPay.sync="payableData"
        :templateOptions="initTableData"
        :templateType="`receivable`"
        :Constatvariable="Constatvariable"
        :templateDelReceveIds="delReceveIds"
        :oldData="oldData.receivableData"
        :verifyShow="verifyShow"
        @getInfo="getPaymentReceivable"
        class="margin-top text-sm"
      ></HotTable>
    </el-card>

    <el-card class="btn-header" v-if="verifyShow.payView">
      <div slot="header" class="clearfix relative">
        <span class="title-icon">应付</span>
        <div v-if="isEdit" class="header-save-btn">
          <el-button
            size="mini"
            type="text"
            style="margin-right: 30px;"
            @click="repairAllPaySynToAmoeba"
          >
            <el-tooltip
              effect="light"
              placement="bottom"
              content="应付(未结转)重新同步到阿米巴"
            >
              <i class="el-icon-refresh" style="font-size:20px"></i>
            </el-tooltip>
          </el-button>
          <el-tooltip
            v-if="verifyShow.editPay"
            effect="light"
            placement="bottom"
            content="复制应付"
          >
            <i
              class="el-icon-document-copy text-blue text-xl margin-right"
              @click="copyPaymentinfo"
            ></i>
          </el-tooltip>
          <el-button
            v-if="verifyShow.createPay"
            type="text"
            size="mini"
            @click="addPayable"
          >
            新增
          </el-button>

          <!-- <el-button type="text" size="mini" @click="savePayable">
            保存
          </el-button> -->
        </div>
      </div>

      <HotTable
        ref="payableHotTable"
        :isEdit="isEdit"
        :templateName="`Payable`"
        :templateData.sync="payableData"
        :templateOptUser="optUser"
        :payToReceve.sync="receivableData"
        :templateOptions="initTableData"
        :Constatvariable="Constatvariable"
        :templateType="`payable`"
        :templateDelPayIds="delPayIds"
        :verifyShow="verifyShow"
        :oldData="oldData.payableData"
        @getInfo="getPaymentReceivable"
        class="margin-top text-sm"
      ></HotTable>
    </el-card>
    <CopyReceivable
      ref="CopyReceivable"
      :templateOptions="initTableData"
      :receivableData.sync="receivableData"
    ></CopyReceivable>
    <CopyPayment
      ref="CopyPayment"
      :templateOptions="initTableData"
      :payableData.sync="payableData"
    ></CopyPayment>
  </div>
</template>

<script>
import { ajax } from "@/store/yg/common/utils";

import { untransform } from "@/store/yg/common/uri";
import { clone } from "@/utils/clone";
import { parseTime, getFindKey } from "@/utils";
import HotTable from "./HotTable";
import CopyReceivable from "./CopyReceivable";
import CopyPayment from "./CopyPayment";
import { m } from "@/store/yg/common/local";

export default {
  components: {
    HotTable,
    CopyReceivable,
    CopyPayment
  },
  props: {
    Constatvariable: {
      type: Object,
      default: function() {
        return {};
      }
    },
    initTableData: {
      type: Object,
      default: function() {
        return {};
      }
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    verifyShow: {
      type: Object,
      default: function() {
        return {};
      }
    }
  },
  data() {
    return {
      //快递总毛重
      totalexpressweight: "",
      collectMap: {},
      fullscreenLoading: false,

      loadingOver: false,
      //当前用户
      optUser: "",
      //记录应收删除的ID
      delReceveIds: [],
      //记录应付删除的ID
      delPayIds: [],
      //应收
      receiveTotalCost: 0,
      //应付
      payTotalCost: 0,
      //利润率
      profit: "0%",
      //应付信息
      payMap: {},
      //应收信息
      receiveMap: {},
      standardCurrency: "RMB",
      restaurants: [],
      selectionList: [],
      selectionPayableList: [],
      isChangeReceivable: false,
      isChangePayable: false,
      //服务商解析管理
      parseServicerMap: {},
      receivableData: [],
      payableData: [],
      action: "",
      feeData: [],
      fileList: [{ name: "", url: "" }],
      uploadShow: false,
      parseServicerId: "",
      oldData: {}
    };
  },

  mounted() {
    this.optUser = this.$store.state.auth.user.name;
    this.getPaymentReceivable();
  },
  methods: {
    repairAllPaySynToAmoeba() {
      var param = {};
      const waybillId = this.$route.query.pid;
      param["id"] = waybillId;
      ajax("repairAllPaySynToAmoeba", param).then(
        res => {
          if (res.code != 200) {
            if (null != res.message) {
              this.$message.error(m(res.message));
            } else {
              this.$message.error("更新失败!");
            }
          } else {
            this.$message.success("更新成功!");
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    repairAllReceiveSynToAmoeba() {
      var param = {};
      const waybillId = this.$route.query.pid;
      param["id"] = waybillId;
      ajax("repairAllReceiveSynToAmoeba", param).then(
        res => {
          if (res.code != 200) {
            if (null != res.message) {
              this.$message.error(m(res.message));
            } else {
              this.$message.error("更新失败!");
            }
          } else {
            this.$message.success("更新成功!");
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    getPaymentReceivable() {
      console.log('this.initTableData["userMap"] :>> ', this.initTableData);
      console.log("this.$route.query.pid :>> ", this.$route.query.pid);
      ajax("queryAbroadPaymentReceivable", {
        id: parseInt(this.$route.query.pid)
      }).then(res => {
        if (res.data && res.data.abroadReceivableList) {
          console.log("res :>> ", res);

          this.payMap = res.data.payMap;
          this.receiveMap = res.data.receiveMap;
          this.payTotalCost = res.data.payTotalCost;
          this.totalProfit = res.data.totalProfit;
          this.receiveTotalCost = res.data.receiveTotalCost;

          this.$nextTick(() => {
            const p = clone(res.data.abroadPaymentList);
            const r = clone(res.data.abroadReceivableList);
            for (const i of p) {
              i.serCusId = this.initTableData["serveCompanyMap"][i.serCusId];
              i.costName = this.initTableData["payNameMap"][i.costName];
              console.log(
                'this.initTableData["userMap"] :>> ',
                this.initTableData
              );
              // console.log("i.inputUser :>> ", i.inputUser);
              i.inputUser = this.initTableData["userMap"][i.inputUser];
              i.lastOperator = this.initTableData["userMap"][i.lastOperator];
              i.billType = i.billType ? "目" : "起";
            }
            for (const i of r) {
              i.serCusId = this.initTableData["customerMap"][i.serCusId];
              i.costName = this.initTableData["payNameMap"][i.costName];
              i.inputUser = this.initTableData["userMap"][i.inputUser];
              i.lastOperator = this.initTableData["userMap"][i.lastOperator];
              i.billType = i.billType ? "目" : "起";
            }
            // console.log("this.receivableData :>> ", this.receivableData);

            this.payableData = p;

            this.receivableData = r;
            this.oldData.payableData = clone(p);
            this.oldData.receivableData = clone(r);
          });
        }
      });
    },

    copyPaymentinfo() {
      this.$refs.CopyPayment.centerDialogVisible = true;
    },
    copyReceivableinfo() {
      this.$refs.CopyReceivable.centerDialogVisible = true;
    },
    chnageUpload() {
      this.uploadShow = true;
    },

    addReceivable() {
      // console.log("this.templateOptions :>> ", this.templateOptions);

      var receive = {
        id: null,
        serCusId: this.initTableData["customerMap"][
          this.Constatvariable.customerId
        ],
        costName: "",
        responsibleId: "",
        inputUser: this.optUser,
        lastOperator: null,
        unitPrice: "",
        count: "",
        currency: "",
        totalCost: "",
        remain: "",
        billType: "目",
        amoebaSubjectId: "",
        accountDate: parseTime(new Date().toLocaleDateString(), "{y}-{m}-{d}"),
        cdate: parseTime(new Date().toLocaleDateString(), "{y}-{m}-{d}"),
        remark: ""
      };
      this.receivableData.push(receive);

      this.oldData.receivableData = clone(this.receivableData);
    },
    addPayable() {
      var payble = {
        id: null,
        serCusId: "",
        costName: "",
        responsibleId: "",
        inputUser: this.optUser,
        lastOperator: null,
        unitPrice: "",
        count: "",
        currency: "",
        totalCost: "",
        remain: "",
        billType: "目",
        amoebaSubjectId: "",
        accountDate: parseTime(new Date().toLocaleDateString(), "{y}-{m}-{d}"),
        cdate: parseTime(new Date().toLocaleDateString(), "{y}-{m}-{d}"),
        remark: ""
      };
      this.payableData.push(payble);
      this.oldData.payableData = clone(this.payableData);
    },

    checkRule(i) {
      if (!i.serCusId) {
        this.$message.error("请填写公司名");
        return false;
      } else if (!i.costName) {
        this.$message.error("请填写费用名称");
        return false;
      } else if (!i.count) {
        this.$message.error("请填写数量");
        return false;
      } else if (!i.currency) {
        this.$message.error("请填写币种");
        return false;
      } else if (!i.unitPrice) {
        this.$message.error("请填写单价");
        return false;
      } else if (!i.billType) {
        this.$message.error("请填写账单类型");
        return false;
      }

      return true;
    },

    submitUpload() {
      this.$refs.upload.submit();
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },

    async savePayable() {
      console.log("this.payableData :>> ", this.payableData);
      const pList = clone(this.payableData);
      console.log("pList :>> ", pList);
      if (pList.length === 0) {
        this.$message.error("请录入数据");
        return;
      }

      console.log("pList :>> ", pList);
      console.log("this.Constatvariable :>> ", this.Constatvariable);
      const waybillNo = this.Constatvariable.waybillNo;
      for (const i of pList) {
        if (!this.checkRule(i)) return;
        i.costOrigini = 1;
        i.waybillId = parseInt(this.$route.query.pid);

        i.waybillNo = waybillNo;

        i.cuser = parseInt(this.$store.state.auth.user.id);

        for (const j in i) {
          if (j === "serCusId") {
            i.serCusId = getFindKey(
              i.serCusId,
              this.initTableData.serveCompanyMap
            );
          } else if (j === "costName") {
            i.costName = getFindKey(i.costName, this.initTableData.payNameMap);
          } else if (j === "inputUser") {
            i.inputUser = getFindKey(i.inputUser, this.initTableData.userMap);
          } else if (j === "lastOperator") {
            i.lastOperator = getFindKey(
              i.lastOperator,
              this.initTableData.userMap
            );
          } else if (j === "billType") {
            i.billType = i.billType === "起" ? 0 : 1;
          }
        }
      }

      const data = await ajax("batchSaveAbroadPayment", {
        paymentList: pList
      });
      if (data.code !== 200) {
        this.$message.error(data.message || "保存失败");
      } else {
        this.$message.success("保存成功！");
        this.getPaymentReceivable();
      }
    },
    async saveReceivable() {
      const rList = clone(this.receivableData);
      console.log("rList :>> ", rList);
      if (rList.length === 0) {
        this.$message.error("请录入数据");
        return;
      }
      for (const i of rList) {
        if (!this.checkRule(i)) return;
        i.costOrigini = 1;
        i.waybillId = parseInt(this.$route.query.pid);
        i.waybillNo = this.Constatvariable.waybillNo;
        i.cuser = parseInt(this.$store.state.auth.user.id);
        for (const j in i) {
          if (j === "serCusId") {
            i.serCusId = getFindKey(i.serCusId, this.initTableData.customerMap);
          } else if (j === "costName") {
            i.costName = getFindKey(i.costName, this.initTableData.payNameMap);
          } else if (j === "inputUser") {
            i.inputUser = getFindKey(i.inputUser, this.initTableData.userMap);
          } else if (j === "lastOperator") {
            i.lastOperator = getFindKey(
              i.lastOperator,
              this.initTableData.userMap
            );
          } else if (j === "billType") {
            i.billType = i.billType === "起" ? 0 : 1;
          }
        }
      }
      const data = await ajax("batchSaveAbroadReceivable", {
        receivableList: rList
      });
      console.log("data :>> ", data);
      if (data.code !== 200) {
        this.$message.error(data.message);
      } else {
        this.$message.success("保存成功！");
        this.getPaymentReceivable();
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.border-lr {
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
}
/deep/ .el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}
</style>
<style>
.handsontable th {
  background: #fff;
  color: #2c3e50;
  text-align: left;
  font-weight: bold;
}

.el-card__body {
  color: #606266;
}
.handsontable th:first-child,
.handsontable th:nth-child(2),
.handsontable td:first-of-type,
.handsontable tr th,
.handsontable tr td,
.handsontable tr:first-child th,
.handsontable tr:first-child td {
  border-color: #ebeef5;
}
</style>
